<style>
  .layui-table-cell .layui-table-sort {
    display: none;
  }

  .import {
    opacity: 0;
    position: absolute;
    width: 69px;
    height: 38px;
    margin-left: -10px;
  }
</style>

<!-- 正文开始 -->
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-card-body">
      <!-- 头部操作栏 -->
      <div class="layui-form lay-header">
        <div class="toolbar">
          <div class="layui-form-item lay-query-content">
            <div class="lay-query-box">
              <div class="query-lt">
                <!--        <div class="layui-inline">
                                    <label class="layui-form-label w-auto">客户名称66666666：</label>
                                    <div class="layui-input-inline">
                                        <input name="factoryName" id="factoryName" class="layui-input"
                                               type="text"
                                               placeholder="请输入客户名称" autocomplete="off"/>
                                    </div>
                                </div>


                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">采购组织：</label>
                                    <div class="layui-input-inline">
                                        <input name="purchaseTissue" id="purchaseTissue" class="layui-input"
                                               type="text"
                                               placeholder="请输入采购组织" autocomplete="off"/>
                                    </div>
                                </div>
-->

                <div class="layui-inline">
                  <label class="layui-form-label w-auto">物料编码：</label>
                  <div class="layui-input-inline">
                    <input name="materialCode" id="materialCode" class="layui-input" type="text" placeholder="请输入物料编码" autocomplete="off" />
                  </div>
                </div>

                <div class="layui-inline">
                  <label class="layui-form-label w-auto">物料名称：</label>
                  <div class="layui-input-inline">
                    <input name="purchaseTissue" id="purchaseTissue" class="layui-input" type="text" placeholder="请输入物料名称" autocomplete="off" />
                  </div>
                </div>

                <div class="layui-inline">
                  <label class="layui-form-label w-auto">计划接收时间：</label>
                  <div class="layui-input-inline">
                    <input id="pTime" class="layui-input date-icon" type="text" placeholder="选择计划接收时间" autocomplete="off" readonly />
                    <input name="startTime" id="startTime" style="display: none" />
                    <input name="endTime" id="endTime" style="display: none" />
                  </div>
                </div>
              </div>
              <div class="query-rt">
                <div class="layui-inline">
                  <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" lay-submit layui-form-keyDownSearch="true">查询</button>
                  <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="lay-btn-rows">
          <div class="lay-btn-box">
            <div class="lay-btn-lt"></div>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <table class="layui-table" id="requirePlanItermInfo" lay-filter="requirePlanItermInfo"></table>
    </div>
  </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="productPlanningTableBar">
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="seePlanItermDetail">详情</a>
  <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="createPlan">创建生产计划</a>
</script>

<!-- js部分 -->
<script>
  layui.use(["layer", "form", "table", "laydate", "admin", "laytpl", "tableTreeDj", "config"], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var table = layui.table;
    var form = layui.form;
    var config = layui.config;
    var admin = layui.admin;
    var tableTree = layui.tableTreeDj;

    //时间范围
    laydate.render({
      elem: "#pTime",
      type: "date",
      range: true,
      done: function (value, date, endDate) {
        if (value) {
          var dateValue = value.split(" - ");
          $("input[name='startTime']").val(dateValue[0] + " 00:00:00");
          $("input[name='endTime']").val(dateValue[1] + " 23:59:59");
        } else {
          $("input[name='startTime']").val("");
          $("input[name='endTime']").val("");
        }
      }
    });

    // 初始化表格
    var insTb = table.render({
      id: "requirePlanItermInfo",
      elem: "#requirePlanItermInfo",
      url: config.base + "production/productionPlan/admin/requirePlanProductSummary/list",
      method: "GET",
      headers: { Authorization: "Bearer " + config.getToken() },
      page: true,
      limits: [10, 20, 30, 40, 50],
      toolbar: false,
      defaultToolbar: ["filter"],
      cellMinWidth: 100,
      cols: [[]], // 初始为空列定义，稍后将被更新
      done: function (res, curr, count) {
        // 分页完成后的回调，这里可以根据需要添加额外逻辑
      }
    });
    // 首次加载时调用函数，传入默认参数
    let params = {};
    renderDynamicTable(params);

    // 加载数据并动态设置表头
    function renderDynamicTable(params) {
      $.ajax({
        url: config.base + "production/productionPlan/admin/requirePlanProductSummary/listHeads",
        method: "GET",
        data: params,
        headers: { Authorization: "Bearer " + config.getToken() },
        success: function (response) {
          let { headers, data, currentPage, pageSize, totalPages, totalCount } = response;

          // 初始化静态列定义
          const staticCols = [
            { type: "numbers", title: "序号", align: "center" },
            { field: "materialCode", title: "物料编码", align: "center" },
            { field: "materialDescribe", title: "物料名称", align: "center" },
            { field: "materialUnit", title: "单位", align: "center" }
          ];

          // 动态添加日期列定义
          const dynamicCols = headers.map((header) => ({
            field: header,
            title: header,
            align: "center"
          }));

          // 定义新列
          const newSumDemandQuantityCol = {
            field: 'sumDemandQuantity', // 根据实际需要替换为你的字段名
            title: '总需求',
            align: 'center',
            width: 100
          };

          // 操作列定义
          const operationCol = {
            align: "center",
            toolbar: "#productPlanningTableBar",
            title: "操作",
            width: 200
          };

          // 合并静态、动态列定义，并将操作列放在最后
          const cols = [staticCols.concat(dynamicCols, [newSumDemandQuantityCol], [operationCol])];

          // 使用 table.render 方法重新渲染表格以应用新的列定义
          insTb = table.render({
            id: "requirePlanItermInfo",
            elem: "#requirePlanItermInfo",
            url: config.base + "production/productionPlan/admin/requirePlanProductSummary/list",
            where: params, // 在这里添加你想要传递的参数对象
            method: "GET",
            headers: { Authorization: "Bearer " + config.getToken() },
            page: true,
            limits: [10, 20, 30, 40, 50],
            toolbar: false,
            defaultToolbar: ["filter"],
            cellMinWidth: 100,
            cols: cols, // 新的列定义
            /*data: data,
            page: {
              curr: currentPage,
              count: totalCount
            },*/
            done: function (res, curr, count) {
              // 分页完成后的回调，这里可以根据需要添加额外逻辑
            }
          });
        },
        error: function (error) {
          console.error("Error fetching table data:", error);
          layer.msg("获取数据失败，请稍后再试", { icon: 2 });
        }
      });
    }

    // 工具条点击事件
    table.on("tool(requirePlanItermInfo)", function (obj) {
      // 将最新分页信息赋值到params中
      params.page = obj.curr;
      params.limit = obj.limit;

      // 重新加载数据
      /*        renderDynamicTable(params);*/

      let data = obj.data;
      if (obj.event === "seePlanItermDetail") {
        //详情
      } else if (obj.event === "createPlan") {
        //创建生产计划
        console.log("obj", data.productDetailId);
      }
    });

    // 搜索
    form.on("submit(formSubSearchLog)", function (data) {
         renderDynamicTable(data.field);
          // 阻止表单默认提交行为
          return false;
      // insTb.reload({where: data.field, page: {curr: 1}}, 'data');
    });

    // 重置搜索
    form.on("submit(resets)", (data) => {
      $(".lay-header").find("select").val("");
      $(".lay-header").find("input").val("");
      let field = data.field;
      for (let key in field) {
        field[key] = "";
      }
      insTb.reload({ where: field, page: { curr: 1 } }, "data");
    });

    // 添加按钮点击事件
    $("#addProductionPlan").click(function () {

    });
  });
</script>
